import axios from 'axios'
import type { AxiosResponse, AxiosError } from 'axios'

// API 接口类型定义
interface ChatContent {
  content: string
  contentType: string
}

interface ChatRequest {
  appId: number
  userId: number
  contents: ChatContent[]
  knowledgeIds: string[]
}

interface StreamResponse {
  contentType: string
  contents: {
    contentType: string
    content: string
  }[]
  roleType: string
  timeSpend: number
  usedToken: number
  isDone: boolean
}
// 统一配置 tenant header 键名
const TENANT_HEADER = 'tenantid' // 根据实际服务端要求修改

// axios 实例配置
const http = axios.create({
  baseURL: 'http://192.168.100.135:38071',
  timeout: 6000000,
  headers: {
    'Content-Type': 'application/json',
    [TENANT_HEADER]: '33'
  }
})

// 请求拦截器
http.interceptors.request.use(config => {
  config.headers[TENANT_HEADER] = '33'
  return config
})

// 响应拦截器
http.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (error: AxiosError) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 解析 SSE 数据（仅用于流式接口）
function parseSSEData(data: string): StreamResponse | null {
  try {
    const jsonStr = data.replace(/^data:/, '').trim()
    return jsonStr ? JSON.parse(jsonStr) : null
  } catch (error) {
    console.error('解析 SSE 数据失败:', error)
    return null
  }
}

// 封装 fetch 方法处理流式响应（仅用于流式接口）
async function fetchSSE(url: string, options: RequestInit & { onMessage: (text: string, toolRes: any) => void }) {
  const { onMessage, ...fetchOptions } = options
  try {
    const response = await fetch(`http://192.168.100.135:38071${url}`, {
      ...fetchOptions,
      headers: {
        'Content-Type': 'application/json',
        ...fetchOptions.headers,
      }
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body?.getReader()
    const decoder = new TextDecoder()

    while (reader) {
      const { value, done } = await reader.read()
      if (done) break
      const text = decoder.decode(value)
      const lines = text.split('\n')
      for (const line of lines) {
        if (line.trim()) {
          const data = parseSSEData(line)
          if (data && data.contents && data.contents.length > 0) {
            onMessage(data.contents[0].content, data.toolExecutedResult)
          }
        }
      }
    }
  } catch (error) {
    console.error('SSE 请求错误:', error)
    throw error
  }
}

export const api = {
  // 流式接口（保持原样）
  async sendMessage(chatRequest: ChatRequest, onProgress: (text: string, toolRes: any) => void) {
    try {
      await fetchSSE('/chat/stream', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          [TENANT_HEADER]: '33'
        },
        body: JSON.stringify(chatRequest),
        onMessage: onProgress
      })
    } catch (error) {
      console.error('发送消息失败:', error)
      throw error
    }
  },

  // 普通接口（修改后）
  async sendMessage2(chatRequest: ChatRequest): Promise<ApiResponse<StreamResponse>> {
    try {
      const response = await http.post('/chat', chatRequest)
      console.log("22222222222222", response);

      return response.data as ApiResponse<StreamResponse>
    } catch (error) {
      console.error('发送消息失败:', error)
      throw error
    }
  },

  // 普通接口（修改后）
  async sendMessage3(chatRequest: ChatRequest): Promise<ApiResponse<StreamResponse>> {
    try {
      const response = await http.post('/chat/structuredOutputsUser', chatRequest)
      console.log("3333333333333333", response);

      return response.data as ApiResponse<StreamResponse>
    } catch (error) {
      console.error('发送消息失败:', error)
      throw error
    }
  },


  async sendMessage4(chatRequest: ChatRequest): Promise<ApiResponse<StreamResponse>> {
    try {
      const response = await http.post('/chat/generateQuestion', chatRequest)
      console.log("4", response);

      return response.data as ApiResponse<StreamResponse>
    } catch (error) {
      console.error('发送消息失败:', error)
      throw error
    }
  },


  //查询建议搜索内容
  async getSuggestions(question: String): Promise<ApiResponse<any>> {
    try {
      const response = await http.get('/chat/suggestSearch', { params: { question } })
      console.log(response);
      return response.data as ApiResponse<any>

    } catch (error) {
      console.error('获取建议失败:', error)
      throw error
    }
  },

  // 获取历史消息（保持原样）
  async getHistory(userId: number): Promise<ApiResponse<any>> {
    try {
      const response = await http.get('/chat/list', { params: { userId } })
      return response.data as ApiResponse<any>
    } catch (error) {
      console.error('获取历史记录失败:', error)
      throw error
    }
  },

  //删除聊天记录
  async clearHistory(chatRequest: ChatRequest): Promise<ApiResponse<any>> {
    console.log("chatRequest", chatRequest);
    try {
      const response = (await http.delete('/chat/delete', { data: chatRequest }))
      return response.data as ApiResponse<any>
    } catch (error) {
      console.error('删除历史记录失败:', error)
      throw error
    }
  }
}

// 错误类型定义
export interface ApiError {
  code: string
  message: string
}

// 响应类型定义
export interface ApiResponse<T = any> {
  code: number
  data: T
  message: string
}